<?php
final class City {
	private $cities;
	private $city_id;
	private $coutry_id;
	private $code;
	private $name;
	
	public function __construct($registry) {
		$this->config = $registry->get('config');
		$this->db = $registry->get('db');
		$this->language = $registry->get('language');
		$this->request = $registry->get('request');
		$this->session = $registry->get('session');
		
		// Load all the city that the system is supported
		$query = $this->db->query("SELECT * FROM " . DB_PREFIX . "city WHERE supported = '1'");

    	foreach ($query->rows as $result) {
      		$this->cities[$result['city_id']] = array(
        		'country_id'         => $result['country_id'],
        		'name'   => $result['name'],
        		'code'   => $result['code']
      		); 
    	}
		
		if (isset($this->request->get['city']) && (array_key_exists($this->request->get['city'], $this->cities))) {
			$this->set($this->request->get['city']);
    	} elseif ((isset($this->session->data['city'])) && (array_key_exists($this->session->data['city'], $this->cities))) {
      		$this->set($this->session->data['city']);
    	} elseif ((isset($this->request->cookie['city'])) && (array_key_exists($this->request->cookie['city'], $this->cities))) {
      		$this->set($this->request->cookie['city']);
    	} else {
      		$this->set($this->config->get('config_city_id'));
    	}
	}
	
	public function set($city) {
    	$this->city_id = $city;
    	$this->name = $this->cities[$city]['name'];
    	$this->country_id = $this->cities[$city]['country_id'];
    	$this->code = $this->cities[$city]['code'];
    	
    	if ((!isset($this->session->data['city'])) || ($this->session->data['city'] != $city)) {
      		$this->session->data['city'] = $city;
    	}

    	if ((!isset($this->request->cookie['city'])) || ($this->request->cookie['city'] != $city)) {
	  		setcookie('city', $city, time() + 60 * 60 * 24 * 30, '/', $this->request->server['HTTP_HOST']);
    	}
  	}
  	
  	public function getCityId(){
  		if(!isset($this->city_id)){
  			// Return Hanoi for default
  			foreach ($this->cities as $city_id => $city_info){
  				if($city_info['code'] == 'HN'){
  					$this->city_id = city_id;
  					$this->session->data['city'] = $city_id;
  					return $city_id;
  				}
  			}
  		}else{
  			return $this->city_id;
  		}
  	}
  	
  	public function getCode($city = '') {
		if (!$city) {
			return $this->cities[$this->city_id]['code'];
		} elseif ($city && isset($this->cities[$city])) {
			return $this->cities[$city]['code'];
		} else {
			return 0;
		}
  	}
  	
  	public function getName(){
  		if(!isset($this->name)){
  			echo "AAAAAA";
  		}
  		return $this->name;
  	}
  	
  	public function getCountryId(){
  		return $this->coutry_id;
  	}
  	
  	public function getCities(){
  		return $this->cities;
  	}
}
?>